
package Presentacion;

import Datos.Conexion;
import Logica.Usuarios;
import java.awt.HeadlessException;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;


/**
 *
 * @author Gisselle Gauto
 */
public class FrmUsuarios extends javax.swing.JFrame {

    public FrmUsuarios() {
        initComponents();
        cargarIconoBackground();    
        cargarUsuario("");
        cargarUsuariost("");
        inhabilitar();
 
    }
    private void limpiar(){
    txtcodigo.setText("");
    txtnombre.setText("");
    txtapellido.setText("");
    txtusuario.setText("");
    txtpass.setText("");
    cboestado.setSelectedIndex(0);
    cborol.setSelectedIndex(0);
    txtnombre.requestFocus();
    }
    
    private void habilitar(){
    txtnombre.setEnabled(true);
    txtapellido.setEnabled(true);
    txtusuario.setEnabled(true);
    txtpass.setEnabled(true);
    cboestado.setEnabled(true);
    cborol.setEnabled(true);
    btncancelar.setEnabled(true);
    btnguardar.setEnabled(true);
    
    }
    
    private void inhabilitar(){
    txtnombre.setEnabled(false);
   txtapellido.setEnabled(false);
    txtusuario.setEnabled(false);
    txtpass.setEnabled(false);
    cboestado.setEnabled(false);
    cborol.setEnabled(false);
    btncancelar.setEnabled(false);
    btnguardar.setEnabled(false);
    
    }
    DefaultTableModel modelo;
    String accion = "Insertar";

          
     private void cargarUsuario(String filtro){
      Conexion sqlserver = new Conexion();
      Connection cnn = sqlserver.conectar();
      String[] titulos = {"Código","Nombre","Apellido","Usuario","Estado","Fecha Creacion"};
      modelo = new DefaultTableModel(null,titulos);
      String [] registro = new String[6];
      
      String sql = "SELECT * FROM usuarios where nombre LIKE '%" + filtro +"%'";
      try 
      {
        Statement st = cnn.createStatement();
        ResultSet rs = st.executeQuery(sql);
        
        while(rs.next()){
            registro[0]= rs.getString("cod_usuario");
            registro[1]= rs.getString("nombre");
            registro[2]= rs.getString("apellido");
            registro[3]= rs.getString("loggin");
            registro[4]= rs.getString("estado");
             registro[5]= rs.getString("fecha_creacion");
        
            
            modelo.addRow(registro);
        }
        tbvista.setModel(modelo);
      } 
      catch (SQLException e) 
      {
      JOptionPane.showMessageDialog(null, e);
        
      }
    }

     
    String id_actualizar ="";
   
    private void asignarcampos(String cod){
      Conexion sqlserver = new Conexion();
      Connection cnn = sqlserver.conectar();

      String sql = "SELECT * FROM usuarios where cod_usuario="+ cod;
      try 
      {
        Statement st = cnn.createStatement();
        ResultSet rs = st.executeQuery(sql);
        if(rs.next()){
            txtcodigo.setText(rs.getString("cod_usuario")) ;
            txtnombre.setText(rs.getString("nombre"));
             txtapellido.setText(rs.getString("apellido"));
             txtusuario.setText(rs.getString("loggin"));
             txtpass.setText(rs.getString("password"));
            cboestado.setSelectedItem(rs.getString("estado"));
            cborol.setSelectedItem(rs.getString("cod_rol"));
            
          
        }
      } 
      catch (SQLException e) 
      {
            JOptionPane.showMessageDialog(null, e);
      }
      id_actualizar = cod;
      
    }  
     
     
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        mnopciones = new javax.swing.JPopupMenu();
        mneditar = new javax.swing.JMenuItem();
        mneliminar = new javax.swing.JMenuItem();
        jTabbedPane2 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtcodigo = new javax.swing.JTextField();
        txtnombre = new javax.swing.JTextField();
        cboestado = new javax.swing.JComboBox();
        btnguardar = new javax.swing.JButton();
        btncancelar = new javax.swing.JButton();
        btnnuevo = new javax.swing.JButton();
        btnsalir = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tbvista = new javax.swing.JTable();
        jLabel6 = new javax.swing.JLabel();
        txtfiltro = new javax.swing.JTextField();
        btnbuscar = new javax.swing.JButton();
        btnlimpiar = new javax.swing.JButton();
        btnagregar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        txtapellido = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        txtusuario = new javax.swing.JTextField();
        txtpass = new javax.swing.JPasswordField();
        jLabel4 = new javax.swing.JLabel();
        cborol = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        tbvista1 = new javax.swing.JTable();
        jLabel7 = new javax.swing.JLabel();
        txtfiltro1 = new javax.swing.JTextField();
        btnbuscar1 = new javax.swing.JButton();
        btnlimpiar1 = new javax.swing.JButton();
        btnsalir1 = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        mneditar.setText("Editar Registro");
        mneditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mneditarActionPerformed(evt);
            }
        });
        mnopciones.add(mneditar);

        mneliminar.setText("Eliminar");
        mneliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mneliminarActionPerformed(evt);
            }
        });
        mnopciones.add(mneliminar);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Registro de Usuarios");

        jPanel1.setOpaque(false);

        jLabel1.setText("Cod. de Usuario:");

        jLabel2.setText("Nombre:");

        jLabel3.setText("Estado:");

        txtcodigo.setEnabled(false);

        cboestado.setEditable(true);
        cboestado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "[Seleccione un estado]", "ACTIVO", "INACTIVO" }));

        btnguardar.setText("Guardar");
        btnguardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnguardarActionPerformed(evt);
            }
        });

        btncancelar.setText("Cancelar");
        btncancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btncancelarActionPerformed(evt);
            }
        });

        btnnuevo.setText("Nuevo");
        btnnuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnnuevoActionPerformed(evt);
            }
        });

        btnsalir.setText("Salir");
        btnsalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnsalirActionPerformed(evt);
            }
        });

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Registros de Tratamientos"));
        jPanel5.setOpaque(false);

        tbvista.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tbvista.setComponentPopupMenu(mnopciones);
        tbvista.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbvistaMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(tbvista);

        jLabel6.setText("Nombre:");

        txtfiltro.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtfiltroKeyPressed(evt);
            }
        });

        btnbuscar.setText("Buscar");
        btnbuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnbuscarActionPerformed(evt);
            }
        });

        btnlimpiar.setText("Limpiar");
        btnlimpiar.setEnabled(false);
        btnlimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnlimpiarActionPerformed(evt);
            }
        });

        btnagregar.setText("Agregar");
        btnagregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnagregarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane3)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtfiltro)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnbuscar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnlimpiar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnagregar, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addGap(4, 4, 4)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtfiltro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnbuscar)
                    .addComponent(btnlimpiar)
                    .addComponent(btnagregar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE))
        );

        jLabel5.setText("Apellido:");

        jLabel8.setText("Usuario:");

        jLabel9.setText("Password:");

        jLabel4.setText("Rol:");

        cborol.setEditable(true);
        cborol.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "[Seleccione un rol]", "1", "2" }));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(btnnuevo, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnguardar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btncancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnsalir, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jLabel1)
                                        .addComponent(jLabel2)
                                        .addComponent(jLabel5)
                                        .addComponent(jLabel8))
                                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtnombre, javax.swing.GroupLayout.PREFERRED_SIZE, 550, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtcodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtapellido, javax.swing.GroupLayout.PREFERRED_SIZE, 550, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtusuario, javax.swing.GroupLayout.PREFERRED_SIZE, 550, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(1, 1, 1)
                                        .addComponent(cboestado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(cborol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addGap(35, 35, 35)
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtpass)))
                        .addGap(0, 6, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1))
                    .addComponent(txtcodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtnombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtapellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtusuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addGap(17, 17, 17)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtpass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cboestado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cborol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnguardar, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
                    .addComponent(btncancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
                    .addComponent(btnnuevo, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
                    .addComponent(btnsalir, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE))
                .addGap(10, 10, 10))
        );

        jPanel5.getAccessibleContext().setAccessibleName("Registros de Usuarios");

        jTabbedPane2.addTab("Registro Usuario", jPanel1);

        jPanel2.setOpaque(false);

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Registros de Tratamientos"));
        jPanel6.setOpaque(false);

        tbvista1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tbvista1.setComponentPopupMenu(mnopciones);
        jScrollPane4.setViewportView(tbvista1);

        jLabel7.setText("Nombre:");

        txtfiltro1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtfiltro1KeyPressed(evt);
            }
        });

        btnbuscar1.setText("Buscar");
        btnbuscar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnbuscar1ActionPerformed(evt);
            }
        });

        btnlimpiar1.setText("Limpiar");
        btnlimpiar1.setEnabled(false);
        btnlimpiar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnlimpiar1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 645, Short.MAX_VALUE)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtfiltro1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnbuscar1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnlimpiar1))
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(txtfiltro1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnbuscar1)
                    .addComponent(btnlimpiar1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32))
        );

        btnsalir1.setText("Salir");
        btnsalir1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnsalir1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnsalir1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, 364, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnsalir1, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel6.getAccessibleContext().setAccessibleName("Registros de Usuarios");

        jTabbedPane2.addTab("Ver Usuarios", jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane2)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane2)
                .addContainerGap())
        );

        jTabbedPane2.getAccessibleContext().setAccessibleName("Registro de Usuarios");

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void mneditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mneditarActionPerformed
        int filasel;
        String id;
        filasel = tbvista.getSelectedRow();              
        try {

            if (filasel == -1) {
                JOptionPane.showMessageDialog(null, "Favor seleccione una fila");
            } else {
               accion = "Editar"; 
               modelo = (DefaultTableModel) tbvista.getModel();
               id= (String) modelo.getValueAt(filasel,0);
               btnnuevo.setEnabled(false);
               habilitar();
               asignarcampos(id);
            }
        } 
        catch (HeadlessException e) {
            JOptionPane.showMessageDialog(null, e);
        }  
    }//GEN-LAST:event_mneditarActionPerformed
  
    
    
    private void btnlimpiar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnlimpiar1ActionPerformed
        txtfiltro1.setText("");
    }//GEN-LAST:event_btnlimpiar1ActionPerformed

    private void txtfiltro1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtfiltro1KeyPressed
    cargarUsuariost(txtfiltro1.getText().trim());
        if (txtfiltro1.getText().length() > 0) {
            btnlimpiar1.setEnabled(true);
        } else {
            btnlimpiar1.setEnabled(false);
        }
    }//GEN-LAST:event_txtfiltro1KeyPressed

    private void btnagregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnagregarActionPerformed

    }//GEN-LAST:event_btnagregarActionPerformed

    private void btnlimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnlimpiarActionPerformed
        limpiar();
        txtfiltro.requestFocus();
    }//GEN-LAST:event_btnlimpiarActionPerformed

    private void btnbuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnbuscarActionPerformed
        cargarUsuario(txtfiltro.getText().trim());
    }//GEN-LAST:event_btnbuscarActionPerformed

    private void txtfiltroKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtfiltroKeyPressed
        cargarUsuario(txtfiltro.getText().trim());
        if (txtfiltro.getText().length() > 0) {
            btnlimpiar.setEnabled(true);
        } else {
            btnlimpiar.setEnabled(false);
        }
    }//GEN-LAST:event_txtfiltroKeyPressed

    private void tbvistaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbvistaMouseClicked
        int filasel = tbvista.getSelectedRow();
        String id = (String) modelo.getValueAt(filasel,0);
        asignarcampos(id);
    }//GEN-LAST:event_tbvistaMouseClicked

    private void btnsalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsalirActionPerformed
        int ban;
         ban = JOptionPane.showConfirmDialog(null, "Realmente quiere salir");

        if (ban == JOptionPane.YES_OPTION) { 
            this.dispose();
        }
        
    }//GEN-LAST:event_btnsalirActionPerformed

    private void btnnuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnnuevoActionPerformed
        limpiar();
        habilitar();
        btnnuevo.setEnabled(false);
    }//GEN-LAST:event_btnnuevoActionPerformed

    private void btncancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btncancelarActionPerformed
        int ban;
        if (accion.equals("Insertar")){
            ban = JOptionPane.showConfirmDialog(null, "Realmente desea cancelar el registro del nuevo usuario?");
        }
        else{
            ban = JOptionPane.showConfirmDialog(null, "Realmente desea cancelar la edición del usuario?");
        }
        if (ban == JOptionPane.YES_OPTION) {
            limpiar();
            inhabilitar();
            btnnuevo.setEnabled(true);
        }
    }//GEN-LAST:event_btncancelarActionPerformed

    private void btnguardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnguardarActionPerformed

        Conexion sqlserver = new Conexion();
        Connection cnn = sqlserver.conectar();

        Usuarios usuario = new Usuarios();
        usuario.setNombre(txtnombre.getText());
        usuario.setApellido(txtapellido.getText());
        usuario.setLoggin(txtusuario.getText());
        usuario.setPassword(txtpass.getText());
        usuario.setEstado(cboestado.getSelectedItem().toString());
        usuario.setCod_rol(Integer.parseInt((String) cborol.getSelectedItem()));
       

        String sql = "";
        String mensaje = "";
        switch (accion) {
            case "Insertar":
            sql = "exec insertar_usuario" + " ?,?,?,?,?,?";
            mensaje = "El  usuario fue registrado satisfactoriamente";
            break;
            case "Editar":
            sql = "exec editar_usuario " + id_actualizar + ",?,?,?,?,?,?";
            mensaje = "El usuario fue modificado satisfactoriamente";
            break;
         
        }
        try {
            PreparedStatement pst = cnn.prepareStatement(sql);
            pst.setString(1, usuario.getNombre());
            pst.setString(2, usuario.getApellido());
            pst.setString(3, usuario.getLoggin());
            pst.setString(4, usuario.getPassword());
            pst.setString(5, usuario.getEstado());
            pst.setInt(6, usuario.getCod_rol());

            int n = pst.executeUpdate();
            if (n > 0) {
                JOptionPane.showMessageDialog(null, mensaje);
                cargarUsuario("");
                cargarUsuariost("");
            }
            cnn.close();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex);
        }
        inhabilitar();
        btnnuevo.setEnabled(true);
    }//GEN-LAST:event_btnguardarActionPerformed

    private void btnbuscar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnbuscar1ActionPerformed
        cargarUsuariost(txtfiltro1.getText().trim());
    }//GEN-LAST:event_btnbuscar1ActionPerformed

    private void btnsalir1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsalir1ActionPerformed
       this.dispose();
    }//GEN-LAST:event_btnsalir1ActionPerformed

    
        public void eliminar (int id){
      	Conexion sqlserver = new Conexion();
      	Connection cnn = sqlserver.conectar();

        Usuarios objeto= new Usuarios();

        objeto.setCod_usuario(id);

        String sql = "DELETE FROM usuarios WHERE cod_usuario = ?";
        String mensaje = "El usuario fue eliminado correctamente";

        try {
            PreparedStatement pst = cnn.prepareStatement(sql);
            pst.setString(1, String.valueOf(objeto.getCod_usuario()));

            int n = pst.executeUpdate();
            if (n > 0) {
                JOptionPane.showMessageDialog(null, mensaje);
                cargarUsuario("");
            }
            cnn.close();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, ex);
        }    
    
    }
    
    private void mneliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mneliminarActionPerformed
   
        int ban = JOptionPane.showConfirmDialog(null, "Realmente desea eliminar el usuario?");
        if (ban == JOptionPane.YES_OPTION) {
            int filasel;
            String id;
            filasel = tbvista.getSelectedRow();
            try {

                if (filasel == -1) {
                    JOptionPane.showMessageDialog(null, "Favor seleccione una fila");
                } else {
                    modelo = (DefaultTableModel) tbvista.getModel();
                    id = (String) modelo.getValueAt(filasel, 0);
                    eliminar(Integer.parseInt(id));
                }

            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }
        }
     

// TODO add your handling code here:
    }//GEN-LAST:event_mneliminarActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FrmUsuarios().setVisible(true);
            }
        });
    }

    private void cargarIconoBackground(){
        setIconImage(new ImageIcon(getClass().getResource("/Imagenes/tooth-button.png")).getImage());
        ((JPanel)getContentPane()).setOpaque(false);
        ImageIcon uno=new ImageIcon(this.getClass().getResource("/Imagenes/background.jpg"));
        JLabel fondo= new JLabel();
        fondo.setIcon(uno);
        getLayeredPane().add(fondo,JLayeredPane.FRAME_CONTENT_LAYER);
        fondo.setBounds(0,0,uno.getIconWidth(),uno.getIconHeight());
    }
      private void cargarUsuariost(String filtro){         
     Conexion sqlserver = new Conexion();
      Connection cnn = sqlserver.conectar();
      String[] titulos = {"Código","Nombre","Apellido","Usuario","Estado", "Fecha Creacion"};
      modelo = new DefaultTableModel(null,titulos);
      String [] registro = new String[6];
      
      String sql = "SELECT cod_usuario,nombre,apellido,loggin,estado, fecha_creacion FROM usuarios where nombre LIKE '%" + filtro +"%'";
      try 
      {
        Statement st = cnn.createStatement();
        ResultSet rs = st.executeQuery(sql);
        
        while(rs.next()){
            registro[0]= rs.getString("cod_usuario");
            registro[1]= rs.getString("nombre");
            registro[2]= rs.getString("apellido");
            registro[3]= rs.getString("loggin");
            registro[4]= rs.getString("estado");
            registro[5]= rs.getString("fecha_creacion");
        
            modelo.addRow(registro);
        }
        tbvista1.setModel(modelo);
      } 
      catch (SQLException e) 
      {
      JOptionPane.showMessageDialog(null, e);
        
      }
    }   
    


    // Variables declaration - do not modify//GEN-BEGIN:variables
    public static javax.swing.JButton btnagregar;
    private javax.swing.JButton btnbuscar;
    private javax.swing.JButton btnbuscar1;
    private javax.swing.JButton btncancelar;
    private javax.swing.JButton btnguardar;
    private javax.swing.JButton btnlimpiar;
    private javax.swing.JButton btnlimpiar1;
    private javax.swing.JButton btnnuevo;
    private javax.swing.JButton btnsalir;
    private javax.swing.JButton btnsalir1;
    private javax.swing.JComboBox cboestado;
    private javax.swing.JComboBox cborol;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTabbedPane jTabbedPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JMenuItem mneditar;
    private javax.swing.JMenuItem mneliminar;
    private javax.swing.JPopupMenu mnopciones;
    private javax.swing.JTable tbvista;
    private javax.swing.JTable tbvista1;
    private javax.swing.JTextField txtapellido;
    private javax.swing.JTextField txtcodigo;
    private javax.swing.JTextField txtfiltro;
    private javax.swing.JTextField txtfiltro1;
    private javax.swing.JTextField txtnombre;
    private javax.swing.JPasswordField txtpass;
    private javax.swing.JTextField txtusuario;
    // End of variables declaration//GEN-END:variables
}
